package model

import (
	"blogdemo/gin/errmsg"
	"github.com/jinzhu/gorm"
)

type User struct {
	gorm.Model
	Username    string `gorm:"type:varchar(20); not null" json:"username"`
	PhoneNumber string `gorm:"type:varchar(11); not null" json:"phoneNumber"`
	Password    string `gorm:"type:varchar(20); not null" json:"password"`
}

// FindUser 检测用户名是否存在
func FindUser(username string) bool {
	var user User
	db.Where("username = ?", username).First(&user)
	if user.Username != "" {
		return true
	}
	return false
}

// FindPhoneNumber 检测手机号是否已注册
func FindPhoneNumber(pNumber string) bool {
	var user User
	db.Where("phone_number = ?", pNumber).First(&user)
	if user.PhoneNumber != "" {
		return true
	}
	return false
}

// CheckPhoneNumber 检查手机号是否符合规范
func CheckPhoneNumber(pNumber string) bool {
	if len(pNumber) != 11 {
		return false
	} else if pNumber[0] != '1' {
		return false
	} else {
		for i := 0; i < len(pNumber); i++ {
			if pNumber[i] < '0' || pNumber[i] > '9' {
				return false
			}
		}
	}
	return true
}

// CheckUserName 检查用户名是否符合规范
func CheckUserName(userName string) bool {
	if len(userName) < 4 || len(userName) > 20 {
		return false
	} else {
		for i := 0; i < len(userName); i++ {
			f1 := false
			f2 := false
			f3 := false
			f4 := false
			if userName[i] >= '0' && userName[i] <= '9' {
				f1 = true
			}
			if userName[i] >= 'A' && userName[i] <= 'Z' {
				f2 = true
			}
			if userName[i] >= 'a' && userName[i] <= 'z' {
				f3 = true
			}
			if userName[i] == '_' {
				f4 = true
			}
			if !(f1 || f2 || f3 || f4) {
				return false
			}
		}
	}
	return true
}

// CheckPassword 检测密码是否符合规范
func CheckPassword(password string) bool {
	if len(password) < 6 || len(password) > 20 {
		return false
	} else {
		for i := 0; i < len(password); i++ {
			if password[i] == ' ' {
				return false
			}
		}
	}
	return true
}

// AddUser 添加用户
func AddUser(theUser *User) int {
	err := db.Create(&theUser).Error
	if err != nil {
		return errmsg.FAIL
	}
	return errmsg.SUCCESS
}

// CheckLogin 检测登录账号密码是否匹配
func CheckLogin(uname string, upassword string) int {
	var user User
	err := db.Where("username = ? and password = ?", uname, upassword).First(&user).Error
	if err != nil {
		return errmsg.PASSWORD_WRONG
	}
	return errmsg.SUCCESS
}

// MatchPhoneNumber 检测找回账号名称与手机号是否匹配
func MatchPhoneNumber(uname string, uphone string, upassword string) int {
	var user User
	err := db.Where("username = ? and phone_number = ?", uname, uphone).First(&user).Error
	if err != nil {
		return errmsg.PNUNBER_WRONG
	}
	upassword = user.Password
	return errmsg.SUCCESS
}

// ReturnPassword 找回密码
func ReturnPassword(uname string) string {
	var user User
	db.Where("username = ?", uname).First(&user)
	return user.Password
}

// UpPassword 修改密码
func UpPassword(user User) int {
	err := db.Model(&user).Where("username = ?", user.Username).Updates(&user).Error
	if err != nil {
		return errmsg.FAIL
	}
	return errmsg.SUCCESS
}
